<template>
  <div class="cart">
    <div class="header">
      <span class="title">购物车</span>
    </div>
    <div class="header-a"></div>
    <div class="cartlist">
      <ul class="cartlist-bigbox" v-if="vif">
        <li>
          <span class="icon-pic">
            <div class="right" @click="modifys" v-show="modify">编辑</div>
            <div class="right" @click="completes" v-show="complete">完成</div>
          </span>
        </li>
        <li class="cartlist-box" v-for="item in cartlist" :key="item.id">
          <span class="iconpic">
            <!-- <input type="checkbox" id="name" v-model="item.ischecked" @change="check_list(index)"> -->
            <label for="name">
              <span class="icons">
                <img :src="images8" class="images8">
              </span>
              <span class="companyname">{{item.shopName}}</span>
            </label>
          </span>
          <div class="blank"></div>
          <div class="paymentgoods">
            <div class="paymentgoods-box">
              <div class="int">
                <input
                  type="checkbox"
                  id="name"
                  v-model="item.ischecked"
                  @change="click_input(item)"
                >
              </div>
              <router-link
                tag="div"
                class="paymentgoods-picture"
                :to="{name:'Detail',
              query:{
                id:item.id
              }
              }"
              >
                <img :src="JSON.parse(item.goodsPic)" class="imgs">
              </router-link>
              <div class="paymentgoods-title" v-show="shows">
                <div class="paymentgoods-title-introduce">{{item.goodsName}}</div>
                <div class="paymentgoods-title-category">{{item.goodsIntro}}</div>
                <div class="price">￥{{((item.goodsTruePrice / 100) * item.buyNum).toFixed(2)}}</div>
                <div class="num">X{{item.buyNum}}</div>
              </div>
              <div class="paymentgoods-title" v-show="showss">
                <div class="paymentgoods-title-introduce">
                  <span class="left" @click="reduceCartitem(item),money()">
                    <span class="reduce" ></span>
                  </span>
                  <input
                    type="number"
                    class="number"
                    value="1"
                    v-on:input="money"
                    v-model="item.buyNum"
                    required="required"
                  >
                  <span class="right" @click="addCatitem(item),money()">
                    <span class="add"></span>
                  </span>
                </div>
                <div class="paymentgoods-title-category">{{item.goodsIntro}}</div>
                <div class="detail" @click="deleteFruits(item)">删除</div>
              </div>
            </div>
          </div>
        </li>
      </ul>
      <div class="elseif" v-else>
        <div class="elsetext">居然还没有订单</div>
        <div class="elsetextcenter">逛一逛，发现更多好物</div>
        <router-link to="./mall">
          <div class="elsetextbottom">去逛逛</div>
        </router-link>
      </div>
      <!-- <ul class="cartlist-bigbox">
        <li>
          <div class="Invalid">已下商品暂时无法购买</div>
        </li>
        <li class="cartlist-box">
          <div class="paymentgoods">
            <div class="paymentgoods-box">
              <div class="int"></div>
              <div class="paymentgoods-picture"></div>
              <div class="paymentgoods-title">
                <div class="paymentgoods-title-introduce">
                  宋词唐诗三百首》马未都亲笔推荐精装插图全彩珍藏版
                  重磅推荐
                </div>
                <div class="paymentgoods-title-category">典藏版（彩色）</div>
                <div class="status">宝贝已经卖光了</div>
                <div class="num">X1</div>
              </div>
            </div>
          </div>
        </li>
        <li>
          <div class="empty">
            <div class="emptytext">清空失效物品</div>
          </div>
        </li>
      </ul>-->
    </div>
    <div class="carttotal">
      <div class="carttotal-box">
        <div class="carttotal-box-all">
          <div class="int">
            <input type="checkbox" id="AllCheck" v-model="checkall" @click="checkedAll()">
          </div>
          <span class="allchoose"  @click="checkedAll()">全选</span>
        </div>
        <div class="carttotal-box-settlement">
          <div class="total">
            合计：
            <span class="totalprice">￥{{totalprice.toFixed(2)}}</span>
          </div>
          <div class="gosettlement" @click="gosettlement">结算</div>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import pic8 from "../../icons/shop.png";
import * as api from "../../request/api.js";
import { MessageBox } from "mint-ui";
import { Toast } from "mint-ui";
export default {
  name: "Home",
  data() {
    return {
      images8: pic8,
      shows: true,
      showss: "",
      complete: "",
      modify: true,
      cartlist: [],
      ids: [],
      checkall: false,
    
      shopids: "",
 
      value: "",
      receiveAddrs: "",
      vif: "",
      shoppingCarts: "",
      totalprice: 0,
      cpmylist: [],
      checklist: [],
      goodsAttrId: ''
    };
  },
  // activated(){
  //     this.init()
  // },
  created() {
    this.init()
 
  },
  // computed: {},
  watch:{
"$route":{  
  handler(route){
    const that=this
    if(route.name=='cart'){
       init()
    }
  },
  deep: true
}
  },
  methods: {
     init(){
          this.$http({
      method: "post",
      url: api.CARTLIST,
      data: { pageNo: 1, pageSize: 10 }
    })
      .then(resp => {
        console.log(resp);
        if (resp.data.data.length > 0) {
          this.vif = true;
        } else {
          this.vif = false;
        }
        resp.data.data.forEach(item => {
          this.cartlist.push({ ischecked: false, ...item })
        });
      })
      .catch(resp => {});
     },
    modifys() {
      this.shows = false;
      this.showss = true;
      this.complete = true;
      this.modify = false;
    },
    completes() {
      this.shows = true;
      this.showss = false;
      this.complete = false;
      this.modify = true;
      if(this.cartlist.length==0){
        this.vif=false
      }
 
    },
    deleteFruits(item) {
      MessageBox.confirm("确定删除吗?")
        .then(action => {
          if (action == "confirm") {
            // console.log(item.buyNum, item.goodsAttrId, api.DELETE);
            this.$http({
              method: "post",
              url: api.DELETE,
              data: {
                buyNum: item.buyNum,
                goodsAttrId: item.goodsAttrId
              }
            }).then(resp => {
              // console.log(resp);
              this.cartlist.splice(item, 1);
            });
          }
        })
        .catch(action => {
          // console.log(action);
        });

      // console.log(item.id);
    },
    gosettlement() {
      // console.log(this.ids);
      this.$http({
        method: "post",
        url: api.WAITPAY,
        data: {
          ids: this.ids
        }
      })
        .then(resp => {
          if (this.ids.length <= 0) {
            return Toast({
              message: "请选择结算商品"
            });
          } else if (resp.data.code == 1000) {
            this.$http({
              method: "post",
              url: api.WEIXINCHATURL,
              data: {
                redirectUrl:
                  "https://api.huaxiahong.net/index.html#/payment?paylist",
                userToken: JSON.parse(localStorage.getItem("token"))
              }
            }).then(resp => {
              // console.log(resp.data.data);
              if (resp.data.success == true) {
                window.location.href = resp.data.data;
              }
            });
          }
          this.$router.push({
            path: "./payment",
            query: {
              ids: this.ids,
              totaleprice:(this.totalprice).toFixed(2)
            }
          });
          // console.log(this.ids);
        })
        .catch(resp => {
          console.log(resp);
        });
    },

    abc: function() {
      var that = this;
      var aaa = that.cartlist.filter(item2 => {
        return item2.ischecked == true;
      });
      aaa.length == that.cartlist.length
        ? (that.checkall = true)
        : (that.checkall = false);
      that.money();
    },
    checkedAll() {
      var that = this;
      if (this.checkall == false) {
        that.cartlist.forEach(item1 => {
          item1.ischecked = true;
          this.ids.push(item1.shoppingCartId);
        });
      } else {
        that.cartlist.forEach(item1 => {
          item1.ischecked = false;
          this.ids = [];
        });
      }
      this.checkall = !this.checkall;
      that.money();
    },

    click_input: function(fruitId) {
      // console.log(fruitId);
      var that = this;
      let idIndex = that.ids.indexOf(fruitId.shoppingCartId);
      if (idIndex >= 0) {
        //如果已经包含了该id, 则去除(单选按钮由选中变为非选中状态)
        this.ids.splice(idIndex, 1);
      } else {
        //选中该checkbox
        this.ids.push(fruitId.shoppingCartId);
      }
      that.abc();
    },
    money: function() {
      var that = this;
      this.totalprice = 0;
      that.cartlist.forEach(item2 => {
        if (item2.ischecked == true) {
          that.totalprice += (item2.goodsTruePrice / 100)* item2.buyNum;
          
        }
      });
      // console.log(that.totalprice);
    },

    reduceCartitem(item) {
      console.log(item.buyNum);
      
      item.buyNum--
      // this.buyNum = item.buyNum;
   
      // console.log(this.buyNum);
      if (item.buyNum <= 1) {
        item.buyNum = 1;
      }
           this.$http({
        method: "post",
        url: api.ADDCART,
        data: {
          buyNum: item.buyNum,
          goodsAttrId: item.goodsAttrId
        }
      })
        .catch(resp => {
       
        })
        .then(resp => {
          console.log(resp);
        });
    },
    addCatitem(item) {
      // console.log(item.goodsAttrId, this.buyNum);
      // item.buyNum=this.buyNum
      item.buyNum++;
      // console.log(this.buyNum);
                 this.$http({
        method: "post",
        url: api.ADDCART,
        data: {
          buyNum: item.buyNum,
          goodsAttrId: item.goodsAttrId
        }
      })
        .catch(resp => {
          
        })
        .then(resp => {
          console.log(resp);
        });
     
    }
  }
};
</script>
<style lang="less" scoped>
@import "../../less/cart.less";
</style>
